import { Component } from '@angular/core';
import { NavParams } from 'ionic-angular';
//import { NavParams, Nav } from 'ionic-angular';
//import { Geolocation } from '@ionic-native/geolocation';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';

declare var BMap;
var map:any;
@Component({
  selector: 'page-map',
  templateUrl: 'map.html'
})
export class MapPage {
  refreshInterval = 5000;
  refreshTask: any;
  user: any = {};
  public person: any;

  myGeo:any;
  myIcon:any;
  myDeviceId:any;
  fDate: any;
  tDate: any;
  fDateStr: any;
  tDateStr: any;

  // id: any;
   personId = null;
  constructor(private rest: RestService,
  //  private nav: Nav,
    public navParams: NavParams,
    public translate: TranslateService,
   // private geolocation: Geolocation
    //public alerCtrl: AlertController,
    //public navCtrl: NavController
  ) {
    this.person = navParams.data;
    this.myDeviceId = navParams.data.device1Id;
    this.personId = this.person.id;
    this.myIcon = new BMap.Icon("assets/icon/favicon.ico", new BMap.Size(32, 32));
  }
  ionViewDidLoad() {

    //Amin: !Important:map_container shoud be called here, it can't be inited in constructor, if called in constructor

    map = new BMap.Map("mapContainer");
    map.setMapStyle({
      styleJson:"/assets/custom_map_config.json"
      }
    );

    map.centerAndZoom('青岛', 13);

    map.enableScrollWheelZoom(true);

    this.myGeo = new BMap.Geocoder();

    var geolocationControl = new BMap.GeolocationControl();

    map.addControl(geolocationControl);

   // this.getLocation();

    this.getTravel();
  }
  getTravel(){
    this.fDate = new Date().getTime() ;//- 86400000 + 8*60*60*1000;
    this.tDate = new Date().getTime() ;//- 86400000 + 8*60*60*1000;
    this.fDateStr = new Date(this.fDate).toISOString();
    this.tDateStr = new Date(this.tDate).toISOString();

    this.fDateStr = this.fDateStr.substr(0, 11) + "00:00:00.000Z";
    this.tDateStr = this.tDateStr.substr(0, 11) + "23:59:59.999Z";
    // const startTime = Math.round(Date.parse(this.fDateStr) / 1000) - 8 * 60 * 60;
    // const endTime = Math.round(Date.parse(this.tDateStr) / 1000) - 8 * 60 * 60;
    const startTime = Date.parse(this.fDateStr);//Math.round(Date.parse(this.fDateStr) / 1000) - 8 * 60 * 60*1000;
    const endTime = Date.parse(this.tDateStr);//Math.round(Date.parse(this.tDateStr) / 1000) - 8 * 60 * 60*1000;
    //console.log('&start='+startTime+'&end='+endTime);
    //  var url ='/api/influx/getCoordinateHistoryByPersonId?personId='+this.personId+"&start=1559529341000&end=1559615741000";
    //this.rest.get(url).subscribe(data => {
    var pointArr = [];
    this.rest.get('/api/influx/getCoordinateHistoryByPersonId?personId='+this.personId+'&start='+startTime+'&end='+endTime).subscribe(data => {
      // this.person = data;
     // console.log(data);
      if(data!=null){
        for (var k = 0; k < data.length; k += 2) {
          var pdata = data[k];
          pointArr.push({
            lng: pdata[2],
            lat: pdata[3]
          });
        }

        // 生成坐标点
        var trackPoint = [];
        for (var i = 0, j = pointArr.length; i < j; i++) {
          trackPoint.push(new BMap.Point(pointArr[i].lng, pointArr[i].lat));
        }

        var total = 0; //总记录数
        var groupCount = 0; //每次转十条
        if (trackPoint.length % 10 > 0) {
          groupCount = (trackPoint.length / 10) + 1;
        } else {
          groupCount = (trackPoint.length / 10);
        }

        // tslint:disable-next-line:no-duplicate-variable
        for (var i = 0; i < groupCount; i++) { //外层循环，有多少组十条
          var pos = new Array();
          // tslint:disable-next-line:no-duplicate-variable
          for (var j = 0; j < 10; j++) { //内层循环，每组十条
            if (total < trackPoint.length) { //不超过总记录数结束
              var point = new BMap.Point(trackPoint[(i * 10) + j].lng, trackPoint[(i * 10) + j].lat);
              pos.push(point);
            }
            total++;
          }

          var convertor = new BMap.Convertor();
          convertor.translate(pos, 1, 5, function (data) {
            if (data.status === 0) {

              var polyArr = [];
              for (var i = 0; i < data.points.length; i++) {
                // map.addOverlay(new BMap.Marker(data.points[i]));
                // map.setCenter(data.points[i]);
                polyArr.push(data.points[i]);
              }
              // 画线
              var polyline = new BMap.Polyline(polyArr, {
                strokeColor: "#1869AD",
                strokeWeight: 3,
                strokeOpacity: 1
              });
              map.addOverlay(polyline);
            }
          });
        }
      }
       /*
      var convertor = new BMap.Convertor();

      // convertor.translate(pointArr, 1, 5, this.translateCallback);
      convertor.translate(trackPoint, 1, 25, function (data) {

        console.log(data);

        if(data.status === 0) {
          var marker = new BMap.Marker(data.points[0]);
        }
      });
*/
     // map.centerAndZoom(trackPoint[0], 15);
/*
      // 画线
      var polyline = new BMap.Polyline(trackPoint, {
        strokeColor: "#1869AD",
        strokeWeight: 3,
        strokeOpacity: 1
      });
      map.addOverlay(polyline);*/
/*
      // 配置图片
      var size = new BMap.Size(26, 26);
      var offset = new BMap.Size(0, -13);
      var imageSize = new BMap.Size(26, 26);
      var icon = new BMap.Icon("/assets/imgs/logo.png", size, {
        imageSize: imageSize
      });

      // 画图标
      for (var i = 0, j = trackPoint.length; i < j; i++) {
        var marker = new BMap.Marker(trackPoint[i], {
          icon: icon,
          offset: offset
        }); // 创建标注
        map.addOverlay(marker);

      }*/
      console.log(pointArr);
    },message=>{
      console.error('Failed to get Coordinate history in: ' + message);
    });

  }
  getLocation() {
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
      //console.log(r.point)
      if(this.getStatus() == true){
        var mk = new BMap.Marker(r.point);
        this.map.addOverlay(mk);//标出所在地
        this.map.panTo(r.point);//地图中心移动
       // console.log('您的位置：'+r.point.lng+','+r.point.lat);
        var point = new BMap.Point(r.point.lng,r.point.lat);//用所定位的经纬度查找所在地省市街道等信息
        var gc = new BMap.Geocoder();
        gc.getLocation(point, function(rs){
        //  var addComp = rs.addressComponents;
        //  console.log(rs.address);//地址信息
        //  console.log("my gps");
        //  console.log(rs);
        //  console.log(rs.address);//弹出所在地址
          let marker = new BMap.Marker(rs.address.H, {icon: this.myIcon});

          map.panTo(rs.address);

          marker.setPosition(rs.address);

          map.addOverlay(marker);
        //  this.map.centerAndZoom(locationPoint, 13);
        });
      }else {
        console.log('failed'+this.getStatus());
      }
    },{enableHighAccuracy: true});

  }


  refresh() {

    var allOverlay = map.getOverlays();
    for(var j = 0;j<allOverlay.length;j++) {
      map.removeOverlay(allOverlay[j]);
    }
    this.getTravel();
      this.rest.get('/api/influx/getCoordinateByPersonId?personId=' + this.person.id).subscribe(data => {
        // this.person = data;
      //  console.log(data);
        if(data!=null) {
      //    console.log(data[2] + "," + data[3]);
          this.addMapMaker(data[2], data[3]);
        }
      },message=>{
        console.error('Failed to get Coordinate By PersonId in: ' + message);
      });
  }

  ionViewDidEnter() {
    this.refresh();
    this.refreshTask = setInterval(() => {
      this.refresh();
    }, this.refreshInterval);
  }
  ionViewWillLeave() {
    if (this.refreshTask) {
      clearInterval(this.refreshTask);
    }
  }
  addMapMaker(lng,lat){
  //  var mk = new BMap.Marker(r.point);
  //  this.map.addOverlay(mk);//标出所在地
  //  this.map.panTo(r.point);//地图中心移动
   // console.log('您的位置：'+lng+','+lat);
    var point = new BMap.Point(lng,lat);//用所定位的经纬度查找所在地省市街道等信息

    //添加gps marker和label
  //  var markergg = new BMap.Marker(point);
  //  this.map.addOverlay(markergg); //添加GPS marker

  //  setTimeout(function(){
      var convertor = new BMap.Convertor();
      var pointArr = [];
      pointArr.push(point);
     // convertor.translate(pointArr, 1, 5, this.translateCallback);
      convertor.translate(pointArr, 1, 5, function (data) {
   //   console.log("trans:");
   //   console.log(data);
   //   console.log();
      if(data.status === 0) {
        var marker = new BMap.Marker(data.points[0]);
        map.addOverlay(marker);
    //    console.log("转换后的百度坐标（正确）");
    //    console.log(data);
        //var label = new BMap.Label("转换后的百度坐标（正确）",{offset:new BMap.Size(20,-10)});
        //marker.setLabel(label); //添加百度label
        map.setCenter(data.points[0]);
      }
    });
  //  }, 1000);
   /*
    var gc = new BMap.Geocoder();
    gc.getLocation(point, function(rs){
      var addComp = rs.addressComponents;
      console.log(rs.address);//地址信息
      console.log("my gps");
      console.log(rs);
      console.log(rs.address);//弹出所在地址
      let marker = new BMap.Marker(rs.address.H, {icon: this.myIcon});

      this.map.panTo(rs.address);

      marker.setPosition(rs.address);

      this.map.addOverlay(marker);*/
  }
  //坐标转换完之后的回调函数
  translateCallback (data){
    console.log("trans:");
    console.log(data);
    if(data.status === 0) {
      var marker = new BMap.Marker(data.points[0]);
      map.addOverlay(marker);
     // console.log("转换后的百度坐标（正确）");
     // console.log(data.points[0]);
      var label = new BMap.Label("转换后的百度坐标（正确）",{offset:new BMap.Size(20,-10)});
      marker.setLabel(label); //添加百度label
      map.setCenter(data.points[0]);
    }
  }
}
